import { useEffect, useMemo, useRef, useState } from "react";
import { useSelector } from "react-redux";
import { Menu, List, Avatar, Form, Input, Button, Col, Row } from "antd";
import { IChatsMessageItem, IChatsUserItem } from "../../../interface/IChats";
import ChatsInstance from "../../../chats/ChatsInstance";
import { FileImageOutlined } from '@ant-design/icons';
import OSS from "ali-oss";
import "./AuthsView.css";
let socket: WebSocket;
const  storeOSS = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5tBP72d4QWj2Rcec4SQ2',
  accessKeySecret: 'fhYHQ9rnOQRRfQN8hl0Mt95TE68zFc',
  bucket: 'xietian2501'
});

export default function AuthsView() {
  const { userList, messageList }: { userList: any[]; messageList: any[] } =
    useSelector((state: any) => state.chats);
  const [activeUser, setActiveUser] = useState(0);
  const [form] = Form.useForm();
  const fileRef=useRef(null);
  const user = useSelector((state: any) => state.user).user;
  useEffect(() => {
    if (!socket) socket = ChatsInstance();
  }, []);

  const users = useMemo(() => {
    if (activeUser === 0 && userList.length > 0) {
      setActiveUser(userList[0].userid);
    }
    return userList.map((item: IChatsUserItem) => {
      return {
        key: item.userid,
        label: item.uname,
        icon: <img src={item.avatar} />,
      };
    });
  }, [userList]);
  useEffect(() => {
    if (activeUser === 0) return;
    socket.send(
      JSON.stringify({
        type: 0x03,
        data: {
          userid: user.userid,
          targetid: activeUser,
        },
      })
    );
  }, [activeUser]);

  const onFinish = (values: any) => {
    console.log(user.userid, activeUser);
    socket.send(
      JSON.stringify({
        type: 0x05,
        data: {
          userid: user.userid,
          targetid: activeUser,
          msgTime: Date.now(),
          msgType: "text",
          message: values.message,
        },
      })
    );
    form.resetFields();
  };
  const fileChangeHandler=()=>{
    if(!fileRef.current) return;
    const files=(fileRef.current as HTMLInputElement).files;
    if(!files || files.length===0) return;
    const file:File=files[0];
    storeOSS.put(file.name,file).then((result)=>{
        // console.log(result.url)
        socket.send(JSON.stringify({
        type: 0x05,
        data: {
          userid: user.userid,
          targetid: activeUser,
          msgTime: Date.now(),
          msgType: "image",
          message: result.url,
        },
      }))
    })
  }
  const getMessage=(item:IChatsMessageItem)=>{
    if(item.msgType==="text"){
      return item.userid!==user.userid ? item.userUname+"说:"+item.message : item.message+":说"+item.userUname.split("").reverse().join("");
    }else if(item.msgType==="image"){
      if(item.userid!==user.userid){
        return (<div><span>{item.userUname}+说:</span><img src={item.message}/></div>)
      }else{
        return (<div><img width={100} src={item.message}/><span>:说{item.userUname.split("").reverse().join("")}</span></div>)
      }
    }
  }

  return (
    <>
      <div style={{ display: "flex" }}>
        <Menu
          defaultSelectedKeys={[activeUser.toString()]}
          defaultOpenKeys={["sub1"]}
          selectedKeys={[activeUser.toString()]}
          mode="inline"
          theme="dark"
          items={users}
          onSelect={(e) => {
            setActiveUser(parseInt(e.key));
          }}
          style={{ width: 200, height: 600 }}
        />

        <div  style={{ width: "100%",height:600,overflow:"auto" }} >
          <List
          itemLayout="vertical"
          bordered={true}
          dataSource={messageList}
         
          renderItem={(item, index) => (
            <div>
              <div style={{ textAlign: "center" }}>
                {new Date(item.msgTime).toTimeString().slice(0, 9)}
              </div>
              <List.Item style={{width:"100%"}} className={item.userid===user.userid ? 'self' : ''}>
                <List.Item.Meta
                  avatar={<Avatar src={item.userAvatar} />}
                  title={getMessage(item)}
                  // title={}
                />
              </List.Item>
            </div>
          )}
        />
        </div>
      </div>
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        style={{ maxWidth: 600, margin: 20 }}
        onFinish={onFinish}
        autoComplete="off"
        form={form}
      >
        <Row>
          <Col span={14}>
            <Form.Item<{ message: string }>
              label="我说："
              name="message"
              rules={[
                { required: true, message: "Please input your username!" },
              ]}
            >
              <Input />
            </Form.Item>
          </Col>
          <Col span={4} style={{textAlign:"center"}}>
              <input type="file" ref={fileRef} style={{display:"none"}} onChange={()=>fileChangeHandler()}/>
              <FileImageOutlined style={{fontSize:30}} onClick={()=>{
                  if(!fileRef.current) return;
                  (fileRef.current as HTMLInputElement).click()
              }}/>
          </Col>
          <Col span={4}>
            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                发送
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </>
  );
}
